<template>
  <div class="detail-container">
    <div>
      <el-steps :active="order.orderStatus + 1" finish-status="success" align-center>
        <el-step title="待付款" />
        <el-step title="待备货" />
        <el-step title="待派送" />
        <el-step title="已完成" />
        <el-step title="已關閉" />
      </el-steps>
    </div>
    <el-card shadow="never" style="margin-top: 10px">
      <div class="operate-container">
        <i class="el-icon-warning color-danger" style="margin-left: 20px" />
        <span class="color-danger">当前订单状态：{{ dict.label.orderStatus[order.orderStatus] }}</span>
        <div class="operate-button-container">
          <el-button size="mini" @click="showNoteVisable = true">添加備註</el-button>
          <el-button size="mini" @click="printReceipt">正式收據</el-button>
          <el-button size="mini" @click="onePrintDocuments">打印</el-button>
          <el-button size="mini" @click="showCancelProductVisable=true;cancelType = 'order'">取消訂單</el-button>
          <el-button
            type="warning"
            size="mini"
            :disabled="!productSelection.length "
            @click="showCancelProductVisable=true;cancelType = 'product'"
          >取消部分商品
          </el-button>
        </div>
      </div>
      <div class="table-layout">
        <el-row>
          <el-col :span="3" class="table-cell-title">订单编号</el-col>
          <el-col :span="3" class="table-cell-title">下單時間</el-col>
          <el-col :span="3" class="table-cell-title">預約派送時間</el-col>
          <el-col :span="3" class="table-cell-title">实际派送时间</el-col>
          <el-col :span="3" class="table-cell-title">用户账号</el-col>
          <el-col :span="3" class="table-cell-title">付款狀態</el-col>
          <el-col :span="6" class="table-cell-title">收货地址/自取地址</el-col>
        </el-row>
        <el-row>
          <el-col :span="3" class="table-cell">{{ order.orderSn }}</el-col>
          <el-col :span="3" class="table-cell">{{ order.createTime }}</el-col>
          <el-col :span="3" class="table-cell">{{ order.deliveryTime }}</el-col>
          <el-col :span="3" class="table-cell">{{ order.actualDeliveryTime }}</el-col>
          <el-col :span="3" class="table-cell">{{ order.memberName }}</el-col>
          <el-col :span="3" class="table-cell">{{ dict.label.paymentStatus[order.paymentStatus] }}</el-col>
          <el-col :span="6" class="table-cell">{{ order | formatAddress }}</el-col>
        </el-row>
        <el-row>
          <el-col :span="3" class="table-cell-title">收货人</el-col>
          <el-col :span="3" class="table-cell-title">支付時間</el-col>
          <el-col :span="3" class="table-cell-title">收貨時間</el-col>
          <el-col :span="3" class="table-cell-title">無貨處理</el-col>
          <el-col :span="3" class="table-cell-title ">總支付金額</el-col>
          <el-col :span="3" class="table-cell-title">支付方式</el-col>
          <el-col :span="6" class="table-cell-title">買家留言</el-col>
        </el-row>
        <el-row>
          <el-col :span="3" class="table-cell">{{ order.receiverName }}</el-col>
          <el-col :span="3" class="table-cell">{{ order.paymentTime }}</el-col>
          <el-col :span="3" class="table-cell">{{ order.receiveTime }}</el-col>
          <el-col :span="3" class="table-cell">{{ order.outStock }}</el-col>
          <el-col :span="3" class="table-cell color-danger">${{ order.totalPayAmount }}</el-col>
          <el-col :span="3" class="table-cell">{{ payType(order.payType) }}</el-col>
          <el-col :span="6" class="table-cell">{{ order.buyerMemo }}</el-col>
        </el-row>
      </div>
      <el-table
        ref="orderItemTable"
        :data="order.orderItems"
        style="width: 100%;margin-top: 10px"
        stripe
        @selection-change="selectionChangeHandler"
      >
        <el-table-column type="selection" />
        <el-table-column label="商品名称">
          <template slot-scope="scope">
            <div>{{ scope.row.nameCn }}
              <el-tag v-if="scope.row.returnStatus" size="mini" type="danger">{{
                scope.row.returnStatus | returnStatus
              }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="市場價" width="120">
          <template slot-scope="scope">
            <div>${{ scope.row.price }}</div>
          </template>
        </el-table-column>
        <el-table-column label="真實金額" width="120">
          <template slot-scope="scope">
            <div>${{ scope.row.realAmount }}</div>
          </template>
        </el-table-column>
        <el-table-column label="商品編號" width="120">
          <template slot-scope="scope">
            {{ scope.row.sku }}
          </template>
        </el-table-column>
        <el-table-column label="数量" width="120">
          <template slot-scope="scope">
            {{ scope.row.productQuantity }}
          </template>
        </el-table-column>
        <el-table-column label="小计" width="120">
          <template slot-scope="scope">
            ${{ scope.row.price * scope.row.productQuantity }}
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 10px;font-size: 12px;text-align:right;margin-right: 45px">
        商品數量合計：<span class="color-danger" style="margin-right: 40px;">{{ order.productNumber }}</span>
        價格合計：<span class="color-danger">${{ order.realAmount }}</span>
      </div>
      <div class="table-layout">
        <el-row>
          <el-col :span="6" class="table-cell-title">商品合計</el-col>
          <el-col :span="6" class="table-cell-title">預付款</el-col>
          <el-col :span="6" class="table-cell-title">當前支付</el-col>
          <el-col :span="6" class="table-cell-title">評論時間</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">${{ order.totalAmount }}</el-col>
          <el-col :span="6" class="table-cell">${{ order.preSaleAmount }}</el-col>
          <el-col :span="6" class="table-cell">
            <span class="color-danger">${{ order.payAmount }}</span>
          </el-col>
          <el-col :span="6" class="table-cell">
            {{ order.commentTime }}
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell-title">運費</el-col>
          <el-col :span="6" class="table-cell-title">膠帶費</el-col>
          <el-col :span="6" class="table-cell-title">優惠券</el-col>
          <el-col :span="6" class="table-cell-title">活動優惠</el-col>
        </el-row>
        <el-row>
          <el-col :span="6" class="table-cell">${{ order.freightAmount }}</el-col>
          <el-col :span="6" class="table-cell">${{ order.bagFee }}</el-col>
          <el-col :span="6" class="table-cell">${{ order.couponAmount || '0' }}</el-col>
          <el-col :span="6" class="table-cell">${{ order.promotionAmount || '0' }}</el-col>
        </el-row>
        <el-row v-if="order.manualOrder">
          <el-col :span="6" class="table-cell-title">訂單來源</el-col>
          <el-col :span="6" class="table-cell-title">操作人</el-col>
          <el-col :span="6" class="table-cell-title">結款方式</el-col>
        </el-row>
        <el-row v-if="order.manualOrder">
          <el-col :span="6" class="table-cell">{{ dict.label.manualOrder[order.manualOrder] }}</el-col>
          <el-col :span="6" class="table-cell">{{ order.username }}</el-col>
          <el-col :span="6" class="table-cell">{{ dict.label.settlementType[order.settlementType] }}</el-col>
        </el-row>
      </div>
      <el-table
        ref="orderItemTable"
        :data="order.note"
        style="width: 100%;margin-top: 10px"
        stripe
      >
        <el-table-column label="備註創建時間">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="備註內容">
          <template slot-scope="scope">
            {{ scope.row.remark }}
          </template>
        </el-table-column>
        <el-table-column label="備註創建人">
          <template slot-scope="scope">
            {{ scope.row.username }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog :visible="showNoteVisable" center width="30%" @close="showNoteVisable = false">
      <div class="dig">添加備註:
        <el-input v-model="updateOrderNote" type="textarea" />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showNoteVisable = false">取 消</el-button>
        <el-button type="primary" @click="updateOrderNotes">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible="showCancelProductVisable" center width="30%" @close="showCancelProductVisable = false">
      <div class="dig">備註:
        <el-input v-model="cancelProductNote" type="textarea" />
      </div>
      <div class="dig">是否回庫:
        <el-switch
          v-model="backDepot"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="true"
          :inactive-value="false"
        />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showCancelProductVisable = false">取 消</el-button>
        <el-button type="primary" @click="cancelOrderType(cancelType)">确 定</el-button>
      </span>
    </el-dialog>

    <div style="position: absolute; opacity:0;">
      <div v-for="(item, index) in printOrder" :id=" 'pdfWrap' + index" :key="index" class="print">
        <div class="invoice">
          <img src="../../../assets/images/Logo_white.png" height="74" width="250" class="invoiceImg" alt="">
          <div class="titleText">藍藍有限公司</div>
          <div class="titleText">客服 : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ item.phone }}</div>
          <div class="titleText">電郵 : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{ item.email }}</div>
          <div class="titleText">地區 : &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; {{
            item.receiverRegion
          }}
          </div>

          <div class="titleText">送貨時間 : &nbsp;&nbsp;&nbsp;{{ item.actualTimeSlot }}</div>
          <div style="margin-top:20px;height:20px;width:95%;border-top: 2px dashed black;" />
          <div class="single">單號: &nbsp; &nbsp; &nbsp; {{ item.orderSn }}</div>
          <div style="margin-top:20px;height:20px;width:95%;border-top: 2px dashed black;" />
          <div style="position:relative;width:240px;height: 30px">
            <div class="positionLeft">商品名稱</div>
            <div class="positionRight">金額</div>
          </div>
          <div v-for="(cate, cateIndex) in item.map" :key="cateIndex" style="margin-bottom: 10mm">
            <div style="margin-bottom: 20px;width:95%;">
              <div style="height:10px;border-bottom: 2px dashed black;width:30%;float:left" />
              <div class="category">{{ cateIndex }}</div>
              <div style="height:10px;border-bottom: 2px dashed black;width:30%;float:right" />
            </div>
            <div
              v-for=" (products, productIndex) in cate"
              :key="productIndex"
              style="position: relative;width:240px;height: 20px;margin-bottom: 25px;"
            >
              <div class="product positionLeft" style="width: 5cm">
                <div>{{ products.upc }} / {{ products.sku }} / {{ products.name }}</div>
                <div>{{ products.productQuantity }} @{{ products.price }}</div>
              </div>
              <div class="price positionRight">{{ products.totalAmount }}</div>
            </div>
          </div>

          <div style="margin-top:20px;height:10px;width:95%;border-top: 2px dashed black;" />
          <div style="height:20px;width:95%;border-top: 2px dashed black;" />

          <div style="position: relative;width:240px;height: 15px">
            <div class="positionLeft">小計</div>
            <div class="positionRight">{{ item.totalAmount }}</div>
          </div>
          <div style="position: relative;width:240px;height: 15px">
            <div class="positionLeft">膠袋費</div>
            <div class="positionRight">{{ item.bagFee }}</div>
          </div>
          <div v-if="item.discountAmount" style="position: relative;width:240px;height: 15px">
            <div class="positionLeft">優惠費用</div>
            <div class="positionRight">{{ item.discountAmount }}</div>
          </div>
          <div style="position: relative;font-weight: bolder;width:240px;height: 10px;margin-top: 15px">
            <div class="positionLeft">總結</div>
            <div class="positionRight">{{ item.totalPayAmount }}</div>
          </div>

          <div style="margin-top:20px;height:10px;width:95%;border-top: 2px dashed black;" />
          <div style="height:20px;width:95%;border-top: 2px dashed black;" />

          <div style="position: relative;width:240px;height: 15px">
            <div class="positionLeft">交易時間</div>
            <div class="positionRight">{{ item.paymentTime }}</div>
          </div>
          <div style="position: relative;width:240px;height: 15px">
            <div class="positionLeft">交易付款</div>
            <div class="positionRight">{{ item.payType }}</div>
          </div>
          <div v-if="item.returnAmount" style="position: relative;width:240px;height: 15px">
            <div class="positionLeft">退款</div>
            <div class="positionRight">{{ item.returnAmount }}</div>
          </div>
          <div style="margin-top:10px;height:10px;width:95%;border-top: 2px dashed black;" />
          <div style="position: relative;width:240px;height: 10px">
            <div class="positionLeft">總產品數量</div>
            <div class="positionRight">{{ item.productNumber }}</div>
          </div>
          <div style="margin-top:10px;font-size: 16px;font-weight: 900;text-align: center">多謝惠顧! THANK YOU!</div>
          <div style="text-align: center">
            <vue-barcode
              v-if="item.orderSn"
              :value="item.orderSn"
              :options="{ height:30,background:'rgba(255,255,255,0)'}"
            >訂單編號
            </vue-barcode>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import crudOrder from '@/api/oms/order'
import mallSet from '@/api/sms/mallSet'
import { downloadFile, setTitle } from '@/utils/index'
import { mapGetters } from 'vuex'
import html2Canvas from 'html2canvas'
import JSPDF from 'jspdf'
import VueBarcode from '@xkeshi/vue-barcode'

export default {
  name: 'OrderDetails',
  components: { VueBarcode },
  filters: {
    formatNull(value) {
      if (value === undefined || value === null || value === '') {
        return '暂无'
      } else {
        return value
      }
    },
    formatPayType(value) {
      if (value === 1) {
        return '支付宝'
      } else if (value === 2) {
        return '微信'
      } else {
        return '未支付'
      }
    },

    formatAddress(order) {
      if (order.deliveryType === 1) {
        return order.receiverDetailAddress
      } else {
        let str = order.receiverRegion
        if (order.receiverStreet != null) {
          str += '  ' + order.receiverStreet
        }
        str += '  ' + order.receiverBuilding
        str += '  ' + order.receiverDetailAddress
        return str
      }
    },
    returnStatus(val) {
      if (val) {
        return '已退'
      } else {
        return
      }
    }
  },
  dicts: ['orderStatus', 'deliveryType', 'paymentStatus', 'manualOrder', 'settlementType', 'payType'],
  data() {
    return {
      id: null,
      order: {},
      printOrder: [],
      moneyInfo: { orderId: null, freightAmount: 0, discountAmount: 0, status: null },
      message: { title: null, content: null },
      closeInfo: { note: null, id: null },
      markInfo: { note: null },
      mallSet: '',
      showNoteVisable: false,
      updateOrderNote: '',
      showCancelProductVisable: false,
      productSelection: [],
      cancelProductNote: '',
      backDepot: true,
      cancelType: 'order'
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },

  created() {
    this.getOrder()
    mallSet.getMallSet().then(res => {
      this.mallSet = res.data
    })
  },
  methods: {
    getOrder() {
      this.id = this.list = this.$route.query.id
      crudOrder.getOne(this.$route.query.id).then(response => {
        if (response.code === 0) {
          this.order = response.data
          this.printOrder = [response.data]
          setTitle(`訂單編號${this.order.orderSn}`)
        } else {
          this.$notify({
            title: '失敗',
            message: response.message,
            type: 'error'
          })
        }
      })
    },

    updateOrderNotes() {
      crudOrder.updateOrderNote({ orderId: this.order.id, note: this.updateOrderNote }).then(res => {
        if (res.code === 0) {
          this.showNoteVisable = false
          this.updateOrderNote = ''
          this.$notify({
            title: '成功',
            message: res.message,
            type: 'success'
          })
          this.getOrder()
        } else {
          this.$notify({
            title: '失敗',
            message: res.message,
            type: 'error'
          })
        }
      })
    },
    payType(val) {
      if (val !== undefined && val.length > 0) {
        let payType = ''
        val.forEach(item => {
          const name = this.dict.label.payType[item]
          payType = `${payType} ${name}`
        })
        return payType
      } else {
        return '無'
      }
    },
    cancelOrderType(type) {
      if (type === 'product') {
        this.cancelItem()
      } else {
        this.cancelOrder()
      }
    },
    cancelOrder() {
      this.$confirm('該操作將取消該訂單,是否繼續?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudOrder.cancel({
          orderId: this.order.id,
          backDepot: this.backDepot,
          remark: this.cancelProductNote
        }).then(res => {
          this.$notify({
            title: res.code === 0 ? '成功' : '失敗',
            message: res.message,
            type: res.code === 0 ? 'success' : 'error'
          })
          if (res.code === 0) {
            this.showCancelProductVisable = false
            this.backDepot = true
            this.cancelProductNote = ''
          }
          this.getOrder()
        })
      })
    },
    cancelItem(row) {
      this.$confirm('該操作將取消該訂單中的商品,是否繼續?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const orderItemIds = this.productSelection.map(item => {
          return item.id
        })
        crudOrder.cancelItem({
          orderId: this.order.id,
          orderItemIds: orderItemIds,
          backDepot: this.backDepot,
          remark: this.cancelProductNote
        }).then(res => {
          this.$notify({
            title: res.code === 0 ? '成功' : '失敗',
            message: res.message,
            type: res.code === 0 ? 'success' : 'error'
          })
          if (res.code === 0) {
            this.showCancelProductVisable = false
            this.backDepot = true
            this.cancelProductNote = ''
          }
          this.getOrder()
        })
      })
    },
    selectionChangeHandler(sel) {
      this.productSelection = sel
    },
    printReceipt() {
      crudOrder.printReceipt({ orderId: this.order.id }).then(res => {
        if (res.code !== undefined && res.code !== 0) {
          this.$notify({
            title: '失敗',
            message: res.message,
            type: 'error'
          })
          return
        }
        downloadFile(res, `訂單${this.order.orderSn}数据`, 'xlsx')
      })
    },
    onePrintDocuments() {
      const ids = [this.order.id]
      crudOrder.printOrder({ orderIds: ids }).then(res => {
        if (res.code === 0) {
          this.printOrder = res.data
          this.$nextTick(() => {
            // 渲染完毕再执行这个，所以才能没有延时的更改
            this.printPdf(this.order.orderSn, 0)
          })
        }
      })
    },
    printPdf(orderSn, index) {
      const id = '#pdfWrap' + index
      const pdfDom = document.querySelector(id) // 这里绑定你要转换的页面
      pdfDom.style.background = '#FFFFFF'
      html2Canvas(pdfDom, {
        // 开始截图,这里可以设置一些截图时的属性
        logging: false,
        // height:3000,
        allowTaint: true,
        taintTest: false,
        useCORS: true,
        dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
        scale: 4 // 按比例增加分辨率
      }).then((canvas) => {
        // 开始将图片转换为PDF
        const pdf = new JSPDF('p', 'mm', [80, 300]) // A4纸，纵向
        const ctx = canvas.getContext('2d')
        const a4w = 80
        const a4h = 300 // A4大小，210mm x 297mm，四边各保留20mm的边距，显示区域170x257
        const imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度
        let renderedHeight = 0
        while (renderedHeight < canvas.height) {
          const page = document.createElement('canvas')
          page.width = canvas.width
          page.height = Math.min(imgHeight, canvas.height - renderedHeight)// 可能内容不足一页

          // 用getImageData剪裁指定区域，并画到前面创建的canvas对象中
          page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
          // 添加图像到页面，保留10mm边距
          pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 1, 1, a4w, Math.min(a4h, a4w * page.height / page.width))
          renderedHeight += imgHeight
          if (renderedHeight < canvas.height) {
            pdf.addPage()
          }// 如果后面还有内容，添加一个空页
          // delete page;
        }
        // const pdfName = orderSn + '.pdf'
        // pdf.save(pdfName)
        pdf.output('dataurlnewwindow')
      })
    }

  }
}
</script>
<style scoped lang="scss">

.detail-container {
width: 95%;
margin: 20px auto;
}

.operate-container {
background: #F2F6FC;
height: 40px;
margin: -20px -20px 0;
line-height: 40px;
}

.operate-button-container {
float: right;
margin-right: 20px
}

.table-layout {
margin-top: 10px;
border-left: 1px solid #DCDFE6;
border-top: 1px solid #DCDFE6;
}

.table-layout >>>.el-row{
  margin-bottom: 0;
}

.table-cell {
height: 25px;
line-height: 25px;
border-right: 1px solid #DCDFE6;
border-bottom: 1px solid #DCDFE6;
padding: 3px;
font-size: 12px;
color: #606266;
text-align: center;
overflow: hidden;
}

.table-cell-title {
border-right: 1px solid #DCDFE6;
border-bottom: 1px solid #DCDFE6;
padding: 3px;
background: #F2F6FC;
text-align: center;
font-size: 12px;
color: #303133;
}

.color-danger {
color: #ff0f19;
}

.dig {
margin-bottom: 20px;
}

.invoice {
width: 100%;
background: rgba(255, 255, 255, 0);
padding: 0 10px;

.invoiceImg {
position: relative;
left: 50%;
transform: translateX(-50%);
margin-top: 30px;
margin-bottom: 20px;
vertical-align: middle;
}

.titleText {
font-size: 12px;
margin-bottom: 5px;
}

.single {
font-size: 26px;
}

.category {
display: inline-block;
width: 35%;
text-align: center;
font-size: 14px;
}
}

.product {
width: 150px;
}

.price {
position: absolute;
right: 0;
}

.positionRight {
position: absolute;
right: 0;
}

.positionLeft {
position: absolute;
left: 0;
}

.print {
font-size: 12px;
margin: 0 auto;
}
</style>
